package com.graduation.community_manager.controller;

import com.graduation.community_manager.common.JWTUtil;
import com.graduation.community_manager.common.MyContextHolder;
import com.graduation.community_manager.common.ResultData;
import com.graduation.community_manager.entity.CmUserEntity;
import com.graduation.community_manager.service.CmUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/login")
public class LoginController {

    @Autowired
    CmUserService cmUserService;

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }

    @ApiOperation(value = "登录")
    @PostMapping("/action")
    public ResultData login(@RequestBody CmUserEntity cmUser){
        CmUserEntity loginUser = cmUserService.login(cmUser);
        //生成token并且返回
        long time = System.currentTimeMillis();
        String token =  JWTUtil.createToken(loginUser.getUserName(),time);
        // 储存token的创建时间
        JWTUtil.saveToken(token,time);

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return ResultData.success("登录成功", map);
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/info")
    public ResultData info(){
        CmUserEntity loginUser = MyContextHolder.get();

        return ResultData.success(null,loginUser);
    }


}
